package org.farrell.EOSCalc;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class CompDbAdapter {
	public static final String KEY_NAME = "comp_name";
	public static final String KEY_CRIT_TEMP = "temperature";
    public static final String KEY_CRIT_PRES = "pressure";
    public static final String KEY_ACENTRIC = "acentric";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "CompDbAdapter";
    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase myDatabase;

    private static final String DATABASE_PATH = "/data/data/org.farrell.EOSCalc/databases/";
    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "critconsts";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {
    	// The database helper is cribbed from ReignDesign
    	
    	private final Context myContext;

        public DatabaseHelper(Context context) {
        	super(context, DATABASE_NAME, null, DATABASE_VERSION);
        	myContext = context;
        }	
     
        public void createDataBase() throws IOException{
        	// first check if the database already exists
        	boolean dbExist = checkDataBase();
     
        	if(dbExist){
        		//it exists, so do nothing
        	}else{
        		//it doesn't exist so create new db
            	this.getReadableDatabase();
     
            	try {
     
        			copyDataBase();
     
        		} catch (IOException e) {
     
            		throw new Error("Error copying database");
     
            	}
        	}
     
        }
     
        private boolean checkDataBase(){
     
        	SQLiteDatabase checkDB = null;
     
        	try{
        		String myPath = DATABASE_PATH + DATABASE_NAME;
        		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
     
        	}catch(SQLiteException e){
     
        		//database does't exist yet.
     
        	}
     
        	if(checkDB != null){
     
        		checkDB.close();
     
        	}
     
        	return checkDB != null ? true : false;
        }
     
        private void copyDataBase() throws IOException{
     
        	//the database is a file in the assets folder of the project
        	InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
     
        	//this is the full path to the database created getReadableDatabase()
        	String outFileName = DATABASE_PATH + DATABASE_NAME;
     
        	//create output stream to the path of the database
        	OutputStream myOutput = new FileOutputStream(outFileName);
     
        	//copy data into the new database
        	byte[] buffer = new byte[1024];
        	int length;
        	while ((length = myInput.read(buffer))>0){
        		myOutput.write(buffer, 0, length);
        	}
     
        	//Close the streams
        	myOutput.flush();
        	myOutput.close();
        	myInput.close();
     
        }
     
        public void openDataBase() throws SQLException{
     
        	//Open the database
            String myPath = DATABASE_PATH + DATABASE_NAME;
        	myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
     
        }
     
        @Override
    	public synchronized void close() {
     
        	    if(myDatabase != null)
        		    myDatabase.close();
     
        	    super.close();
     
    	}
     
    	@Override
    	public void onCreate(SQLiteDatabase db) {
     
    	}
     
    	@Override
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     
    	}
    }

    public CompDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public CompDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        try {

        	mDbHelper.createDataBase();

        } catch (IOException ioe) {

        	throw new Error("Unable to create database");

        }

        try {

        	mDbHelper.openDataBase();

        }catch(SQLException sqle){

        	throw sqle;

        }
        return this;
    }

    public void close() {
        mDbHelper.close();
    }



    public long createComp(String comp_name, Double temperature, Double pressure, Double acentric) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, comp_name);
        initialValues.put(KEY_CRIT_TEMP, temperature);
        initialValues.put(KEY_CRIT_PRES, pressure);
        initialValues.put(KEY_ACENTRIC, acentric);

        return myDatabase.insert(DATABASE_TABLE, null, initialValues);
    }

    public boolean deleteComp(long rowId) {

        return myDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor fetchAllComps() {

        return myDatabase.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_CRIT_TEMP,
                KEY_CRIT_PRES, KEY_ACENTRIC}, null, null, null, null, null);
    }

    public Cursor fetchComp(long rowId) throws SQLException {

        Cursor mCursor =

            myDatabase.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_NAME, KEY_CRIT_TEMP, KEY_CRIT_PRES, KEY_ACENTRIC}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    public boolean updateComp(long rowId, String comp_name, Double temperature, Double pressure, Double acentric) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, comp_name);
        args.put(KEY_CRIT_TEMP, temperature);
        args.put(KEY_CRIT_PRES, pressure);
        args.put(KEY_ACENTRIC, acentric);

        return myDatabase.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
	
	
}

